'use strict'

import axios from 'axios'
import router from '../router'
import store from '../store'
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL: process.env.VUE_APP_API_BASE_URL
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
}

const _axios = axios.create(config)

_axios.interceptors.request.use(
  function (config) {
    store.commit('loadingAdd')

    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = 'Bearer ' + token;
    }
    // Do something before request is sent
    return config
  },
  function (error) {
    store.commit('loadingSub')
    // Do something with request error
    return Promise.reject(error)
  },
)

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    store.commit('loadingSub')

    // Do something with response data
    if ([401, -3].includes(response.data.code)) {
      router.push('/login')
    }
    return response
  },
  function (error) {
    store.commit('loadingSub')

    // Do something with response error
    return Promise.reject(error)
  },
)

export default {
  install: (Vue, options) => {
    Vue.axios = _axios
    window.axios = _axios
    Object.defineProperties(Vue.prototype, {
      axios: {
        get () {
          return _axios
        },
      },
      $axios: {
        get () {
          return _axios
        },
      },
    })
  }
}

export {
  _axios as axios
}